package com.frogs.ucenter.v1.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.util.StringUtil;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.UserIntegralBalanceDao;
import com.frogs.ucenter.dao.UserRechargeBalanceDao;
import com.frogs.ucenter.entity.UserIntegralBalance;
import com.frogs.ucenter.entity.UserRechargeBalance;
import com.frogs.ucenter.util.Constants;
import com.frogs.ucenter.v1.request.OperationCenterRequest;
import com.frogs.ucenter.v1.request.UserRechargeBalanceShowRequest;
import com.frogs.ucenter.v1.request.UserRechargeBalanceVerifyRequest;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.response.UserPropertyResponse;
import com.frogs.ucenter.v1.service.UserRechargeBalanceService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userRechargeBalanceService")
public class UserRechargeBalanceServiceImpl extends UserRechargeStrategyBaseServiceImpl implements UserRechargeBalanceService {
	
	private Logger log = LoggerFactory.getLogger(UserRechargeBalanceServiceImpl.class);

	@Resource
	private UserRechargeBalanceDao userRechargeBalanceDao;
	@Resource
	private UserIntegralBalanceDao userIntegralBalanceDao;
	
	/**
	 * 获取用户当前余额
	 */
	@Override
	public Response showUserRechargeBalance(Request request) throws Exception {
		UserRechargeBalanceShowRequest showRequest = (UserRechargeBalanceShowRequest)request;
		ShowResponse<BigDecimal> showResponse = new ShowResponse<BigDecimal>();
		try {
			int userId = showRequest.getUserId();
			String orderId = showRequest.getOrderId();
			BigDecimal blockingMoney = new BigDecimal("0.00");
			UserRechargeBalance userRechargeBalance = getUserBalance(userId);
			
			//订单存在冻结金额
			if(!StringUtil.isEmpty(orderId)) {
				blockingMoney = showBlockingMoney(orderId);
			}
				
			if(null != userRechargeBalance) {
				showResponse.setInfo(userRechargeBalance.getBalance().add(blockingMoney));
			} else {
				showResponse.setInfo(new BigDecimal("0.00").add(blockingMoney));
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return showResponse;
	}
	
	/**
	 * 校验用户当前余额
	 */
	@Override
	public Response verifyUserRechargeBalance(Request request) throws Exception {
		UserRechargeBalanceVerifyRequest verifyRequest = (UserRechargeBalanceVerifyRequest)request;
		DefaultResponse response = new DefaultResponse();
		try {
			int userId = verifyRequest.getUserId();
			getUserBalance(userId);
			response.setTip("校验成功!");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	private UserRechargeBalance getUserBalance(Integer userId) throws Exception {
		UserRechargeBalance userRechargeBalance = userRechargeBalanceDao.selectById(userId);
		if(userRechargeBalance != null) {
			BigDecimal balance = userRechargeBalance.getBalance();
			String encryptBalance = userRechargeBalance.getEncryptBalance();
			if (!StringUtil.md5(userId + balance.toString(), Constants.ENCRYPT_BALABCE_KEY).equals(encryptBalance)) {
				throw new ServiceOperationException("当前余额存在异常，请联系客服");
			}
		}
		return userRechargeBalance;
	}

	@Override
	public Response getUserProperty(Request request) throws Exception {
		UserPropertyResponse response = new UserPropertyResponse();
		try {
			OperationCenterRequest centerRequest = (OperationCenterRequest) request;
			int userId = centerRequest.getUserId();
			UserRechargeBalance userRechargeBalance = getUserBalance(userId);
			
			if(null != userRechargeBalance) {
				response.setMoneyBalance(userRechargeBalance.getBalance());
			}
			
			UserIntegralBalance integralBalance = userIntegralBalanceDao.selectById(userId);
			if (integralBalance != null) {
				response.setIntegralBalance(integralBalance.getIntegralUsable());
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
}